package com.example.util;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

public class TimeUtil {

    static DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static String timestampToString(Timestamp time) {
        return df.format(time);
    }

    /**
     * convert string time to timestamp
     * 
     * @param time 5/11/2021 12:21:02 PM or 2021-5-11 12:21:02
     * @return Timestamp
     */
    public static Timestamp stringToTimestamp(String time) {
        Date date = null;
        int[] datePart = null, timePart = null;
        String[] parts = time.split(" ");
        int year, month, day;
        if (time.contains("/")) {
            if (parts.length == 3) {
                String APMarker = parts[2];
                datePart = Arrays.stream(parts[0].split("/")).mapToInt(Integer::parseInt).toArray();
                timePart = Arrays.stream(parts[1].split(":")).mapToInt(Integer::parseInt).toArray();
                if (APMarker.equals("PM")) {
                    timePart[0] = timePart[0] + 12;
                    if (timePart[0] >= 24) {
                        datePart[1] += 1;
                    }
                }
                year = datePart[2];
                month = datePart[0];
                day = datePart[1];
            } else {
                System.out.println("can not convert string:" + time + " to Timestamp, wrong former");
                return null;
            }
        } else if (time.contains("-")) {
            if (parts.length == 2) {
                datePart = Arrays.stream(parts[0].split("-")).mapToInt(Integer::parseInt).toArray();
                timePart = Arrays.stream(parts[1].split(":")).mapToInt(Integer::parseInt).toArray();
                year = datePart[0];
                month = datePart[1];
                day = datePart[2];
            } else {
                System.out.println("can not convert string:" + time + " to Timestamp, wrong former");
                return null;
            }
        } else {
            System.out.println("can not convert string:" + time + " to Timestamp, wrong former");
            return null;
        }
        Calendar c = Calendar.getInstance();
        c.set(year, month - 1, day, timePart[0], timePart[1], timePart[2]);
        date = c.getTime();
        return new Timestamp(date.getTime());
    }

    /**
     * formate time string from 5/11/2021 12:21:02 PM to 2021-5-12 00:21:02
     * 
     * @param date
     * @return
     */
    public static String formatString(String date) {
        Timestamp time = stringToTimestamp(date);
        return timestampToString(time);
    }

    public static String getCurrentTime() {
        String time = df.format(new Date());
        return time;
    }
}
